package com.amos.muexamcore.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * Copyright © 2018 五月工作室. All rights reserved.
 *
 * @Package com.amos.muexamcore.util
 * @ClassName SpringUtils
 * @Description TODO
 * @Author Amos
 * @Modifier
 * @Date 2020/3/21 22:52
 * @Version 1.0
 **/
@Configuration
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return SpringUtils.applicationContext;
    }

    /**
     * 根据class获取对应的的Bean
     *
     * @param clazz Bean的class对象
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 根据beanName获取对应的Bean
     *
     * @param beanName bean的名称
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName) {
        return (T) getApplicationContext().getBean(beanName);
    }
}
